const {getAccessToken, sign, encText} = require('../../utils/util');
const fs = require('fs');
const request = require('request');
let config = require('../../config/config');
/**
 * 体质辨识API(旧版本接口，仅供参考)-提交检测
 * @param req
 * @param resq
 * @param next
 * @returns {Promise<void>}
 */
module.exports = async (req, resq, next) => {
    // 1.获取accessToken
    let accessToken = await getAccessToken();
    // 2.准备待检测的数据：第三方单据id、舌面图片、舌下图片、年龄、性别和结果接收地址
    let outId = 1;
    let age = 20; // 大于等于0
    let sex = 1; // 0：未知 1：男 2：女
    let returnUrl = 'http://k218d99927.iask.in:57804/tongue/constitution/callback';
    let imageFile = fs.createReadStream('./images/tongue.jpg');
    let backImageFile = fs.createReadStream('./images/tongueBack.jpg');

    // 3.加密和签名数据
    let signature = sign(outId);
    let sourceData = {
        age: age,
        sex: sex
    };
    let encryptData = encText(JSON.stringify(sourceData));
    // 4.上传检测
    request.post({
        url: config.tongueSimpleTaskUrl,
        encoding: null,
        formData: {
            outId: outId,
            returnUrl: returnUrl,
            signature: signature,
            encryptData: encryptData,
            images: imageFile,
            backImages: backImageFile
        },
        headers: {"Authorization": "Bearer " + accessToken},
        json: true
    }, (err, response, body) => {
        if (!err) {
            // 当body.code=0表示上传成功：
            // （1）body.data表示预计等待检测时间，
            // （2）检测的结果会回传到您设置的returnUrl上
            console.log(body);
            resq.json(body)
        } else {
            resq.json(err)
        }
    })
}
